#include <sqlite3.h>
#include "../entity/user.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>



static int callback(void* data,int columns,char** rows,char** columnNames){
  User* loginUser = (User *)data;
  for(int i = 0;i<columns;i++){
    printf("%d::%s=%s\n",i,columnNames[i],rows[i]);
    }
      loginUser->id = atoi (rows[0]);
      printf("id==>%d\n",loginUser->id);

      strcpy(loginUser->name,rows[1]);
      //strcpy (loginUser->name, rows[i]);
      printf("name==>%s\n",loginUser->name);
     strcpy(loginUser->password,rows[2]);
      //strcpy (loginUser->name, rows[i]);
      printf("password==>%s\n",loginUser->password);
  
  return 0;
}

int login(const char* name,const char* password,User* loginUser){
  printf("id=%d,name=%s\n",loginUser->id,loginUser->name);
  
  //user->name = "admin";
  //user->password = "123456";
  
  //打开数据库
  sqlite3 *db;
  char* errMsg;
  char* sql;
  int res = sqlite3_open("mydb.db",&db);
  //返回0代表成功
  if(res){
    fprintf (stderr, "打开数据库错误:%s\n",sqlite3_errmsg(db));
    return -1;
  }
   sql = sqlite3_mprintf ("select id,name,password from user where name='%q' and password='%q'",name,password);
  printf("sql=%s\n",sql);
  res = sqlite3_exec(db,sql,callback,loginUser,&errMsg);
  if(res!=SQLITE_OK){
    printf("执行SQL语句有误：%s\n", errMsg);
    sqlite3_free(errMsg);
  }
  sqlite3_close (db);  
  printf("数据库关闭成功1...\n");
   printf("id=%d,name=%s\n",loginUser->id,loginUser->name);    
  printf("数据库关闭成功2...\n");
  
  return 0;
}

